<template>
  <main class="main-content">
    <!-- 1. 页面头部 -->
    <a-page-header class="page-header" :title="pageTitle" @back="goBack">
      <template #extra>
        <a-space>
          <a-button @click="fetchDeviceDetail" :loading="loading">刷新状态</a-button>
          <a-button type="primary">更新设备信息</a-button>
        </a-space>
      </template>
    </a-page-header>
    
    <!-- 2. 主内容区 -->
    <div class="content-wrapper">
      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane key="deviceInfo" tab="设备信息"></a-tab-pane>
        <a-tab-pane key="runtimeStatus" tab="运行状态"></a-tab-pane>
        <a-tab-pane key="videoChannels" tab="视频通道"></a-tab-pane>
        <a-tab-pane key="aiModels" tab="模型列表"></a-tab-pane>
        <a-tab-pane key="eventRecords" tab="事件记录"></a-tab-pane>
      </a-tabs>

      <!-- Tab 内容面板 -->
      <div class="tab-content">
        <a-skeleton :loading="loading" active :paragraph="{ rows: 10 }">
          <!-- A. 设备信息 Tab -->
          <div v-if="activeTab === 'deviceInfo'">
            <a-descriptions :column="2" layout="horizontal" bordered size="middle">
              <a-descriptions-item label="设备名称" :span="2">{{ device.name || '-' }}</a-descriptions-item>
              <a-descriptions-item label="设备描述" :span="2">{{ device.description || '-' }}</a-descriptions-item>
              <a-descriptions-item label="产品类型/型号">{{ device.model || '-' }}</a-descriptions-item>
              <a-descriptions-item label="设备标识(SN)">{{ device.sn || '-' }}</a-descriptions-item>
              <a-descriptions-item label="安装日期">{{ device.installDate || '-' }}</a-descriptions-item>
              <a-descriptions-item label="安装位置">{{ device.locationName || '-' }}</a-descriptions-item>
              <a-descriptions-item label="创建时间">{{ formatDateTime(device.createdAt) }}</a-descriptions-item>
              <a-descriptions-item label="维护责任人">{{ device.maintainer || '-' }}</a-descriptions-item>
              <!-- 【核心改造】照片展示 -->
              <a-descriptions-item label="设备照片" :span="2">
                <a-spin :spinning="photoLoading">
                  <div v-if="device.photos && device.photos.length > 0">
                    <a-image-preview-group>
                      <a-image
                        v-for="(photoUrl, index) in photoUrls"
                        :key="index"
                        :width="104"
                        :height="104"
                        :src="photoUrl"
                        class="device-photo"
                      />
                    </a-image-preview-group>
                  </div>
                  <a-empty v-else description="暂无照片" />
                </a-spin>
              </a-descriptions-item>
            </a-descriptions>
          </div>

          <!-- B. 运行状态 Tab -->
          <div v-if="activeTab === 'runtimeStatus'">
            <a-descriptions :column="2" layout="horizontal" bordered size="middle">
              <a-descriptions-item label="设备状态">
                <a-badge :status="getStatusType(device.status)" :text="formatStatus(device.status)" />
              </a-descriptions-item>
              <a-descriptions-item label="最近在线时间">{{ formatDateTime(device.lastOnline) }}</a-descriptions-item>
              <a-descriptions-item label="IP 地址">{{ device.ipAddress }}:{{ device.port }}</a-descriptions-item>
              <a-descriptions-item label="运行时长">{{ device.runtimeDuration || '--' }}</a-descriptions-item>
              <a-descriptions-item label="CPU 使用率">{{ device.cpuUsage ? `${device.cpuUsage}%` : '--' }}</a-descriptions-item>
              <a-descriptions-item label="内存使用率">{{ device.memoryUsage ? `${device.memoryUsage}%` : '--' }}</a-descriptions-item>
              <a-descriptions-item label="硬件版本">{{ device.hardwareVersion || '-' }}</a-descriptions-item>
              <a-descriptions-item label="固件版本">{{ device.softwareVersion || '-' }}</a-descriptions-item>
            </a-descriptions>
          </div>

          <!-- C. 视频通道 Tab -->
          <div v-if="activeTab === 'videoChannels'">
            <a-table :columns="channelColumns" :data-source="channelList" :loading="channelLoading" :pagination="false" row-key="id" bordered>
               <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'status'">
                    <a-badge :status="record.status === 1 ? 'success' : 'error'" :text="record.status === 1 ? '在线' : '离线'" />
                  </template>
               </template>
            </a-table>
          </div>
          
          <!-- D. 模型列表 Tab (卡片风格) -->
          <div v-if="activeTab === 'aiModels'">
            <a-spin :spinning="modelLoading">
              <a-list
                v-if="modelList && modelList.length > 0"
                :grid="{ gutter: 24, xs: 1, sm: 2, md: 3, lg: 4 }"
                :data-source="modelList"
              >
                <template #renderItem="{ item }">
                  <a-list-item>
                    <a-card hoverable class="model-card">
                      <a-card-meta :title="item.name">
                        <template #description>
                          <p class="model-desc">模板: {{ item.templateCode }}</p>
                          <p class="model-desc">版本: {{ item.version }}</p>
                        </template>
                      </a-card-meta>
                    </a-card>
                  </a-list-item>
                </template>
              </a-list>
              <a-empty v-else description="该设备未配置AI模型" />
            </a-spin>
          </div>

          <!-- E. 事件记录 Tab (带查询和分页) -->
          <div v-if="activeTab === 'eventRecords'">
            <div class="event-filter-bar">
              <a-space>
                <a-select v-model:value="eventFilters.eventType" placeholder="所有事件类型" style="width: 150px" allow-clear>
                  <a-select-option value="人员入侵">人员入侵</a-select-option>
                  <a-select-option value="车辆越界">车辆越界</a-select-option>
                </a-select>
                <a-range-picker v-model:value="eventFilters.dateRange" show-time />
                <a-button type="primary" @click="fetchEvents({ resetPage: true })">查询</a-button>
              </a-space>
            </div>
            <a-table
              :columns="eventColumns"
              :data-source="eventList"
              :loading="eventLoading"
              :pagination="eventPagination"
              row-key="id"
              bordered
              @change="handleEventTableChange"
            />
          </div>
        </a-skeleton>
      </div>
    </div>
  </main>
</template>

<script setup>
import { ref, onMounted, computed, reactive, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getDeviceDetail, getDeviceChannels, getDeviceModels, getDeviceEvents  } from '@/api/device';
import { getProtectedImage } from '@/api/files';
import { message } from 'ant-design-vue';
import { FileImageOutlined } from '@ant-design/icons-vue';

// --- 基础状态 ---
const route = useRoute();
const router = useRouter();
const device = ref({}); // 存储设备核心信息
const loading = ref(true); // 主信息加载状态
const activeTab = ref('deviceInfo');
const deviceId = computed(() => route.params.id);
const pageTitle = computed(() => `设备详情 - ${device.value.name || '加载中...'}`);


const photoLoading = ref(false); // 新增照片加载状态
const photoUrls = ref([]); // 存储可访问的图片 Blob URL


// --- 子 Tab 页状态 ---
const channelList = ref([]);
const channelLoading = ref(false);
const modelList = ref([]);
const modelLoading = ref(false);
const eventList = ref([]);
const eventLoading = ref(false);
const eventFilters = reactive({ eventType: undefined, dateRange: [] });
const eventPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
});

// --- 表格列定义 ---
const channelColumns = [
  { title: '通道号', dataIndex: 'id', key: 'id', width: 80 },
  { title: '通道名称', dataIndex: 'name', key: 'name' },
  { title: '主码流地址', dataIndex: 'mainStreamUrl', key: 'mainStreamUrl' },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
];
const eventColumns = [
  { title: '事件时间', dataIndex: 'eventTime', key: 'eventTime', width: 200 },
  { title: '事件类型', dataIndex: 'eventType', key: 'eventType', width: 150 },
  { title: '事件级别', dataIndex: 'eventLevel', key: 'eventLevel', width: 100 },
  { title: '事件详情', dataIndex: 'details', key: 'details' },
];


// --- API 调用逻辑 ---
const fetchDeviceDetail = async () => {
  loading.value = true;
  photoLoading.value = true;
  try {
    const response = await getDeviceDetail(route.params.id);
    device.value = response.data;
    // 【核心改造】异步加载所有受保护的图片
    if (device.value.photos && device.value.photos.length > 0) {
      const promises = device.value.photos.map(url => getProtectedImage(url));
      photoUrls.value = await Promise.all(promises);
    }
  } catch (error) {
    message.error('获取设备详情失败！');
  } finally {
    loading.value = false;
    photoLoading.value = false;
  }
};

const fetchChannels = async () => {
  channelLoading.value = true;
  try {
    const response = await getDeviceChannels(deviceId.value);
    channelList.value = response.data;
  } catch (error) {
    message.error('获取视频通道列表失败！');
  } finally {
    channelLoading.value = false;
  }
};

const fetchModels = async () => {
  modelLoading.value = true;
  try {
    const response = await getDeviceModels(deviceId.value);
    modelList.value = response.data;
  } catch (error) {
    message.error('获取模型列表失败！');
  } finally {
    modelLoading.value = false;
  }
};

const fetchEvents = async ({ resetPage = false } = {}) => {
  if (resetPage) eventPagination.current = 1;
  eventLoading.value = true;
  try {
    const params = {
      page: eventPagination.current - 1,
      size: eventPagination.pageSize,
      eventType: eventFilters.eventType,
      startTime: eventFilters.dateRange?.[0]?.toISOString(),
      endTime: eventFilters.dateRange?.[1]?.toISOString(),
      sort: 'eventTime,desc',
    };
    const response = await getDeviceEvents(deviceId.value, params);
    eventList.value = response.data.content.map(event => ({
      ...event,
      eventTime: formatDateTime(event.eventTime),
    }));
    eventPagination.total = response.data.totalElements;
  } catch (error) {
    message.error('获取事件记录失败！');
  } finally {
    eventLoading.value = false;
  }
};


// --- 事件处理 ---
const goBack = () => router.push('/devices/list');
const handleEventTableChange = (pager) => {
  eventPagination.current = pager.current;
  eventPagination.pageSize = pager.pageSize;
  fetchEvents();
};

const loadDataForActiveTab = (tabKey) => {
    switch (tabKey) {
    case 'videoChannels':
      
      if (channelList.value.length === 0) fetchChannels();
      break;
    case 'aiModels':
      if (modelList.value.length === 0) fetchModels();
      break;
    case 'eventRecords':
      if (eventList.value.length === 0) fetchEvents();
      break;
    default:
      // deviceInfo 和 runtimeStatus 的数据已在 fetchDeviceDetail 中获取
      break;
  }
}

// --- 侦听器，实现 Tab 懒加载 ---
watch(activeTab, (newTab) => {
    loadDataForActiveTab(newTab);
});


// --- 生命周期钩子 ---
onMounted(() => {
  fetchDeviceDetail();
});


// --- 辅助函数 ---
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-';
  return new Date(dateTimeString).toLocaleString('zh-CN', { hour12: false }).replace(/\//g, '-');
};
const formatStatus = (status) => {
  const map = { ONLINE: '在线', OFFLINE: '离线', UNINITIALIZED: '未初始化' };
  return map[status] || '未知';
};
const getStatusType = (status) => {
  const map = { ONLINE: 'processing', OFFLINE: 'error', UNINITIALIZED: 'warning' };
  return map[status] || 'default';
};
</script>

<style scoped>
.main-content {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 64px); /* 视口高度 - 头部高度 */
  background-color: #f0f2f5;
}

.page-header {
  background-color: #fff;
  padding: 16px 24px;
  flex-shrink: 0;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-page-header-heading) {
  width: 100%;
}
:deep(.ant-page-header-heading-extra) {
  margin-left: auto !important;
  /* 按钮组与页面右边缘的距离 */
  padding-right: 16px; 
}

.content-wrapper {
  background-color: #fff;
  margin: 24px;
  padding: 0 24px 24px 24px;
  flex-grow: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.tab-content {
  margin-top: 24px;
}

.photo-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 24px;
  background-color: #fafafa;
  border-radius: 4px;
  color: #bfbfbf;
}
.photo-placeholder p {
  margin-top: 8px;
  margin-bottom: 0;
}

.model-card {
  border: 1px solid #f0f0f0;
}
.model-card :deep(.ant-card-meta-description) {
  color: rgba(0, 0, 0, 0.45);
}
.model-desc {
    margin-bottom: 4px;
}

.event-filter-bar {
  margin-bottom: 16px;
}

:deep(.ant-descriptions-item-label) {
  width: 160px; /* 加宽以容纳长标签 */
  text-align: right;
  background-color: #fafafa !important;
  color: #595959;
}
:deep(.ant-table-bordered .ant-table-thead > tr > th),
:deep(.ant-table-bordered .ant-table-tbody > tr > td) {
  border-right: none;
}

/* 【新增】设备照片样式 */
.device-photo {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  margin-right: 8px;
  margin-bottom: 8px;
  object-fit: cover; /* 确保图片不变形 */
}

</style>